package server;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.Executors;

public class Server
{

    HttpServer httpServer;
    public static Map<Object, Object> PlayerList;

    public Server()
    {
        try
        {
            PlayerList = new LinkedHashMap<>();
            InetSocketAddress address = new InetSocketAddress("localhost", 8001);
            httpServer = HttpServer.create(address, 10);
            httpServer.createContext("/", new Handler());
            httpServer.setExecutor(Executors.newFixedThreadPool(10));
            httpServer.start();
            System.out.println("Server started...");            
        } catch (IOException ex)
        {
            ex.printStackTrace();
        }
    }
    
    public void stop()
    {
        httpServer.stop(0);
    }

    class Handler implements HttpHandler
    {

        @Override
        public void handle(HttpExchange t) throws IOException
        {
            String resp = "";
            String request = getRequest(t);
            ClientProcessor processor = null;
            String[] message = request.split("\\^");
            if (message[0].equals("login") && (isLoginTaken(message[1]) == true))
            {
                resp = "login^NO";
            } else
            {
                for (Entry<Object, Object> entry : PlayerList.entrySet())
                {
                    Player player = (Player) entry.getKey();
                    if (message[1].equals(player.name))
                    {
                        processor = (ClientProcessor) entry.getValue();
                    }
                }
                if (processor == null)
                {
                    Player player = new Player();
                    player.name = message[1];
                    player.status = "free";
                    processor = new ClientProcessor(player);
                    PlayerList.put(player, processor);
                }
                resp = processor.processClient(request);
            }
            sendResponse(t, resp);
        }

        private boolean isLoginTaken(String login)
        {
            boolean ret = false;
            for (Entry<Object, Object> entry : PlayerList.entrySet())
            {
                Player player = (Player) entry.getKey();
                if (login.equals(player.name)) //if there is already a player with such login
                {
                    ret = true;
                    break;
                }
            }
            return ret;
        }
    }

    public String getRequest(HttpExchange t)
    {
        String ret = null;
        try
        {
            InputStream is = t.getRequestBody();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            ret = rd.readLine();
            rd.close();
            is.close();
        } catch (IOException ex)
        {
            ex.printStackTrace();
        }
        return ret;
    }

    public void sendResponse(HttpExchange t, String resp)
    {
        try
        {
            StringBuilder response = new StringBuilder().append(resp);
            t.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.length());
            t.getResponseBody().write(response.toString().getBytes());
            t.getResponseBody().close();
            t.close();
        } catch (IOException ex)
        {
            ex.printStackTrace();
        }
    }

    public static void main(String[] args)
    {
        new Server();
    }
}
